package com.example.officialdocumentsys.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.officialdocumentsys.annotation.LogAnno;
import com.example.officialdocumentsys.common.R;
import com.example.officialdocumentsys.common.ThreadLocalContext;
import com.example.officialdocumentsys.po.User;
import com.example.officialdocumentsys.service.UserService;
import com.example.officialdocumentsys.utils.ValidateCodeUtils;
import com.example.officialdocumentsys.vo.UserVO;
import com.google.code.kaptcha.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生信息 前端控制器
 * </p>
 *
 * @author hi
 * @since 2022-11-17
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User, UserService>{

    @LogAnno(operateType = "浏览用户")
    @GetMapping("/page")
    public R<Page> list(int page, int pageSize, String name) {
        Page<UserVO> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<UserVO> eLambdaQueryWrapper = new LambdaQueryWrapper<>();
        eLambdaQueryWrapper.like(StringUtils.isNotBlank(name),User::getRealName,name);
        return R.success(baseService.getVO(pageInfo,eLambdaQueryWrapper));
    }
    @LogAnno(operateType = "浏览用户")
    @GetMapping("/pagePlus")
    public R<Page> pagePlus(int page, int pageSize, String name,Integer sex,Integer status) {
        LambdaQueryWrapper<UserVO> qw = new LambdaQueryWrapper<>();
        qw.eq(status != null,User::getStatus,status);
        qw.eq(sex != null,User::getSex,sex);
        qw.eq(User::getRole,1);
        qw.like(StringUtils.isNotBlank(name),User::getRealName,name);
        Page<UserVO> pageInfo = new Page(page, pageSize);
        return R.success(baseService.getVO(pageInfo,qw));
    }

    @LogAnno(operateType = "用户浏览自己")
    @GetMapping("/self")
    public R<Page> self(int page, int pageSize, String name) {
        Page<UserVO> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<UserVO> eLambdaQueryWrapper = new LambdaQueryWrapper<>();
        eLambdaQueryWrapper.eq(User::getId, ThreadLocalContext.getCurrentId());
        return R.success(baseService.getVO(pageInfo,eLambdaQueryWrapper));
    }

    @LogAnno(operateType = "登入")
    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody Map map) {
        String password = map.get("password").toString();
        String userId = map.get("userName").toString();
        Long role = Long.valueOf(map.get("role").toString());
        //判断角色
        if (role == null){
            return R.error("角色不可为空");
        }
        //查找验证码
        if(session.getAttribute(Constants.KAPTCHA_SESSION_KEY) == null){
            return R.error("验证码失效");
        }
        //比对验证码
        String vailCode = session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
        String code = map.get("code").toString();
        if(!code.equals(vailCode)){
            return R.error(session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString());
        }
        //1.md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userId).eq(role == 0,User::getRole,role);
        User user1 = baseService.getOne(queryWrapper);

        //3.判断是否存在用户
        if(user1 == null){
            return R.error("用户不存在");
        }

        //4.比对密码
        if(!user1.getPassword().equals(password)){
            return R.error("密码错误");
        }

        //5.查询用户状态
        if(user1.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6.登入成功
        session.setAttribute("user", user1.getId());

        return R.success(user1);
    }

    //登出

    @LogAnno(operateType = "登出")
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("登出成功");
    }


    @LogAnno(operateType = "忘记密码")
    @GetMapping("/forget")
    public R<String> forget(@RequestParam String phone, HttpSession session){
        if(StringUtils.isNotBlank(phone)){
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("手机验证码{}", code);
            session.setAttribute(phone, code);
            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }


    @LogAnno(operateType = "修改密码")
    @PostMapping("/alterPassword")
    public R<String> alterPassword(@RequestBody Map map,HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String password = map.get("newPassword").toString();
        Object attribute = session.getAttribute(phone);
        //校验验证码
        if(attribute != null && attribute.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getTel, phone);
            User one = baseService.getOne(queryWrapper);
            if(one == null){
                return R.error("手机号不存在");
            }
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            one.setPassword(password);
            baseService.updateById(one);
            return R.success("修改成功");
        }
        return R.error("失败");
    }


    @LogAnno(operateType = "注册")
    @PostMapping("/register")
    public R<String> register(@RequestBody Map map,HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String password = map.get("newPassword").toString();
        String userName = map.get("userName").toString();
        Long roleId = Long.valueOf(map.get("roleId").toString());
        Integer sex = Integer.valueOf(map.get("sex").toString());
        String email = map.get("stuEmail").toString();
        Object attribute = session.getAttribute(phone);

        //校验验证码
        if(attribute != null && attribute.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.or().eq(User::getTel, phone).or().eq(User::getRealName,userName);
            User one = baseService.getOne(queryWrapper);
            //判断是否已经存在
            if(one == null){
                one = new User();
                Long ID = IdWorker.getId();
                password = DigestUtils.md5DigestAsHex(password.getBytes());
                one.setTel(phone);
                one.setPassword(password);
                one.setRealName(userName);
                one.setUserName(userName);
                one.setId(ID);
                one.setStatus(1);
                one.setRole(roleId);
                one.setEmail(email);
                one.setSex(sex);
                //保存用户
                baseService.save(one);
                session.removeAttribute(phone);
                return R.success("注册成功！");
            }
            session.removeAttribute(phone);
            return R.error("手机号或账号名已被使用！");
        }
        session.removeAttribute(phone);
        return R.error("验证码有误！");
    }

    @Override
    public R<String> delete(@RequestParam List<Serializable> ids){
        for(Serializable id :ids){
            if(id.equals(ThreadLocalContext.getCurrentId().toString())){
                return R.error("你不能删除你自己");
            }
        }
        baseService.removeByIds(ids);
        return R.success("修改成功");
    }

    @Override
    public R<String> save(@RequestBody User e) {
        //密码为空设置默认密码
        if (e.getPassword() == null){
            String password = "132456abc";
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            e.setPassword(password);
        }
        long id = IdWorker.getId();
        e.setId(id);
        baseService.save(e);

        return R.success("保存成功");
    }


    @Override
    public R<User> detail(@RequestParam Serializable id) {
        User e = baseService.getById(id);
        if (e != null && e.getStatus() == 1) {
            return R.success(e);
        }
        return R.error("没有对应数据或账户不可用");
    }

    @LogAnno(operateType = "禁止用户")
    @GetMapping("/ban")
    public R<String> ban(String id){
        User e = baseService.getById(id);
        //禁用或者解禁用户
        e.setStatus(e.getStatus() == 1 ? 0 : 1);
        baseService.updateById(e);
        return R.success("成功");
    }

    @GetMapping("/listAll")
    public R<List<User>> listAll(){
        QueryWrapper<User> qw = new QueryWrapper<>();
        return R.success(baseService.list(qw));
    }


}

